package com.gdk.ksoft.ui.mores;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.*;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.gdk.ksoft.R;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.ui.logins.DownloadTableActivity;
import com.gdk.ksoft.assembly.receiver.ExitAppReceiver;
import com.gdk.ksoft.assembly.utils.TaskUtils;
import com.gdk.ksoft.assembly.utils.extensions.ControlUtils;
import com.gdk.ksoft.assembly.utils.listener.OnClearListener;
import com.gdk.ksoft.assembly.utils.system.ApkUtils;
import com.gdk.ksoft.assembly.utils.system.ConfigUtils;
import com.gdk.ksoft.assembly.utils.system.FileUtils;
import com.gdk.ksoft.assembly.utils.system.PhoneUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

/**
 * 软件设置页面
 */
public class SoftwareSettingsActivity extends Activity {

    public final static String URL_ACTION = "ACTION_URL";//存储连接地址的字段名

    @ViewInject(R.id.psoftwareSettings_etActionUrl)private EditText etActionUrl;//链接地址输入框
    @ViewInject(R.id.psoftwareSettings_etPhoneIMEI)private EditText etPhoneIMEI;//手机串号输入框

    private ConfigUtils configUtils;//数据配置对象
    private boolean isAllExit = false;//是否是完全退出

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_software_settings);
        ViewUtils.inject(this);
        configUtils = ConfigUtils.getInstance(this);
        if(configUtils.getSharedPreference().contains(URL_ACTION))//如果包含这些数据，则读取
            etActionUrl.setText(configUtils.getSharedPreference().getString(URL_ACTION,""));
        try {
            etPhoneIMEI.setText(PhoneUtils.getDeviceId(this));//获取手机的IMEI
        }catch (Exception e){
            etPhoneIMEI.setText("不能获取到该设备的标识字符串!");
        }
    }

    /**
     * 视图点击事件
     * @param view
     */
    @OnClick(value={R.id.psoftwareSettings_txtSaveSettings,R.id.psoftwareSettings_txtClearCache,
    R.id.psoftwareSettings_txtClearWork})
    public void onViewClick(View view){
        switch(view.getId()){
            case R.id.psoftwareSettings_txtSaveSettings:
                String urlAction = etActionUrl.getText().toString();
                String url = "http://"+ urlAction+"/Mobile/CheXiao/";
                if(TextUtils.isEmpty(urlAction)){
                    Toast.makeText(this,"数据连接地址不能为空!",Toast.LENGTH_SHORT).show();
                    return;
                }
                configUtils.getEditor().putString(URL_ACTION,urlAction).commit();
                SystemData.BASE_URL = url;//设置当前的连接地址为输入的连接
                Toast.makeText(this,"数据连接地址保存成功!",Toast.LENGTH_SHORT).show();
                setResult(RESULT_OK);
                goBack();//页面返回
                break;
            case R.id.psoftwareSettings_txtClearCache:
                TaskUtils.sendMessageToBackgroundService(this, false);//关闭后台上传服务，以防清除数据的时候卡数据库线程
                configUtils.getEditor().putString(DownloadTableActivity.DOWNLOAD_DATE_TIME,"").commit();//清除日期数据
                Toast.makeText(this,"缓存清除成功!",Toast.LENGTH_SHORT).show();
                this.finish();
                ApkUtils.restartApplication(this);//重启应用
                break;
            case R.id.psoftwareSettings_txtClearWork://清理工作和数据库，清理后需要重启软件
                executeClearAllDataTask(this);//执行清理所有数据的任务
                break;
        }
    }

    /**
     * 执行清理所有数据的任务
     */
    public void executeClearAllDataTask(final Context context){
        new AsyncTask<Void,Void,Void>(){
            private String errMessage = null;
            private ProgressDialog dialog = null;
            private Handler handler = null;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在清理中...");
                handler = new Handler(){
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        if(msg.what == 0x0001){
                            dialog.setMessage("正在清理缓存文件："+msg.obj);
                        }
                    }
                };
            }
            @Override
            protected Void doInBackground(Void... params) {
                try{
                    TaskUtils.sendMessageToBackgroundService(context,false);//关闭后台上传服务，以防清除数据的时候卡数据库线程
//                    SharedPreferences.Editor editor = configUtils.getEditor();//获得数据编辑器
//                    editor.putString(DownloadTableActivity.DOWNLOAD_DATE_TIME, "");//清除日期数据
//                    editor.putString(LoginActivity.PASSWORD_FIELD, "");
//                    editor.commit();//清空登录密码
                    FileUtils.clearCache("/data/data/"+context.getPackageName()+"/",new OnClearListener() {
                        @Override
                        public void onClearListener(String filename) {
                            handler.obtainMessage(0x0001,filename).sendToTarget();
                        }
                    });
                }catch (Exception e){
                    e.printStackTrace();
                    errMessage = e.getMessage();
                }
                return null;
            }
            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                if(errMessage!=null){
                    Toast.makeText(context,"清理工作和数据库成失败，请重试!",Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(context,"清理工作完成!正在退出软件，请手动重启!",Toast.LENGTH_SHORT).show();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            resetApplication();//重启应用程序
                        }
                    },2000);
                }
            }
        }.execute();
    }

    /**
     * 重启应用程序
     */
    public void resetApplication(){
        try {
            isAllExit = true;//完全退出
            Intent intent = new Intent(ExitAppReceiver.ACTION);
            sendBroadcast(intent);//通知应用程序退出
            ApkUtils.backToDesktop(this);//回到桌面
            SoftwareSettingsActivity.this.finish();
        }catch (Exception e){
            e.printStackTrace();
            ControlUtils.showToast(this,"系统遇到异常，请手动重启!", Gravity.CENTER,Toast.LENGTH_SHORT);
        }
    }

    /**
     * 页面返回
     */
    public void goBack() {
        this.finish();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }

    @OnClick(value = {R.id.psoftwareSettings_txtBack})
    public void OnBackClick(View view) {
        goBack();//页面返回
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            goBack();//页面返回
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(isAllExit){//如果是完全退出

        }
    }
}
